<?php
namespace pay;
class Pay{
  	public  $Pay_url = 'https://syb.allinpay.com/apiweb/h5unionpay/unionorder';
  	
  	
	/**
	 * 将参数数组签名
	 */
	public static function SignArray(array $array,$appkey){
		$array['key'] = $appkey;// 将key放到数组中一起进行排序和组装
		ksort($array);
		$blankStr = Pay::ToUrlParams($array);
		$sign = md5($blankStr);
		return $sign;
	}
	
	public static function ToUrlParams(array $array)
	{
		$buff = "";
		foreach ($array as $k => $v)
		{
			if($v != "" && !is_array($v)){
				$buff .= $k . "=" . $v . "&";
			}
		}
		
		$buff = trim($buff, "&");
		return $buff;
	}
	
	/**
	 * 校验签名
	 * @param array 参数
	 * @param unknown_type appkey
	 */
	public static function ValidSign(array $array,$appkey){
		$sign = $array['sign'];
		unset($array['sign']);
		$array['key'] = $appkey;
		$mySign = Pay::SignArray($array, $appkey);
		return strtolower($sign) == strtolower($mySign);
	}
  	
   /**
    +----------------------------------------------------------
   * 生成随机字符串
    +----------------------------------------------------------
   * @param int       $length  要生成的随机字符串长度
   * @param string    $type    随机码类型：0，数字+大小写字母；1，数字；2，小写字母；3，大写字母；4，特殊字符；-1，数字+大小写字母+特殊字符
    +----------------------------------------------------------
   * @return string
    +----------------------------------------------------------
   */
  	public function randCode($length = 5, $type = 0) {
        $arr = array(1 => "0123456789", 2 => "abcdefghijklmnopqrstuvwxyz", 3 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4 => "~@#$%^&*(){}[]|");
        if ($type == 0) {
            array_pop($arr);
            $string = implode("", $arr);
        } elseif ($type == "-1") {
            $string = implode("", $arr);
        } else {
            $string = $arr[$type];
        }
        $count = strlen($string) - 1;
        $code = '';
        for ($i = 0; $i < $length; $i++) {
            $code .= $string[rand(0, $count)];
        }
        return $code;
    }

  	public function Pay_request($param){
      	$key = '15774809666';
		$param['cusid'] = '560194048169RWX';
      	$param['appid'] = '00178254';
      	$param['version'] = '12';
      	$param['charset'] = 'UTF-8';
      	$param['returl'] = 'http://cfymkj58.com/ymkj/Payapi/returl'; //同步支付成功跳转地址
      	$param['notify_url'] = 'http://cfymkj58.com/ymkj/Payapi/notify_url'; //异步通知地址
      	$param['randomstr'] = $this->randCode(9,2);
      	//签名，设为signMsg字段值。
		$signMsg = $this->SignArray($param,$key);//签名
     	$param['sign'] = $signMsg;
      	$param['key'] = $key;
      	
      	$aPOST = array();
        foreach($param as $key=>$val){
        	$aPOST[] = $key."=".urlencode($val);
        }
        $strPOST =  join("&", $aPOST);
		return $strPOST;
      
    }


	
}
?>